package com.learn.eduuserboot.controller;

import afu.org.checkerframework.checker.igj.qual.I;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.learn.eduapi.entity.ResponseDTO;
import com.learn.eduapi.entity.order.UserCourseOrder;
import com.learn.eduapi.entity.user.User;
import com.learn.eduapi.entity.user.UserAdmin;
import com.learn.eduuserboot.service.UserAdminService;
import com.learn.eduuserboot.service.UserService;
import com.learn.eduuserboot.until.MD5Util;
import com.learn.eduuserboot.until.RandomCharecters;
import com.learn.eduuserboot.until.ValidateUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 后台账号登录
 */
@RestController
@CrossOrigin
@RequestMapping("user")
public class AdminUserController {
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private UserService userService;

    /**
     * 后台管理登录
     *
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    @GetMapping("adminlogin")
    public ResponseDTO<UserAdmin> adminlogin(@RequestParam("username") String username, @RequestParam("password") String password) throws Exception {
        ResponseDTO<UserAdmin> responseDTO = new ResponseDTO<>();
        UserAdmin userAdmin = userAdminService.login(username);
        System.out.println("userAdmin = " + userAdmin);
        if (userAdmin != null) {
            String salt = userAdmin.getSalt();
            String pwd = salt + password;
            String md5 = MD5Util.md5Encode(password);
            if (userAdmin.getPassword().equals(md5) == true) {
                responseDTO.setMessage("欢迎管理员登录");
                responseDTO.setState(200);
                responseDTO.setContent(userAdmin);
            } else {
                responseDTO.setMessage("账号或密码不正确");
                responseDTO.setState(300);
            }
        } else {
            responseDTO.setMessage("该账号不存在");
            responseDTO.setState(500);
        }
        return responseDTO;
    }

    /**
     * 更新个人信息
     * @param userId
     * @param img
     * @param name
     * @return
     * @throws Exception
     */
    @GetMapping("updateAdminUser")
    public ResponseDTO<UserAdmin> updateAdminUser(@RequestParam("userId") String userId,
                                                  @RequestParam("fileId") String img,
                                                  @RequestParam("name")String name) throws Exception {
        QueryWrapper<UserAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("id", userId);
        UserAdmin userAdmin = new UserAdmin();
        if (img.length()>10){
            userAdmin.setImg(img);
        }
        userAdmin.setName(name);
        int update = userAdminService.update(userAdmin, wrapper);
        ResponseDTO<UserAdmin> responseDTO = new ResponseDTO<>();
        if (update!=1){
            responseDTO.setState(500);
            responseDTO.setMessage("更新个人信息失败");
        }else {
            responseDTO.setState(200);
            responseDTO.setMessage("更新个人信息成功");
        }
        return responseDTO;
    }

    /**
     * 停用启用账号
     * @param userId
     * @param statusId
     * @return
     */
    @GetMapping("StateChanged/{userId}/{statusId}")
    public ResponseDTO<UserAdmin> StateChanged(@PathVariable("userId")Integer userId,
                                               @PathVariable("statusId")String statusId){
        System.out.println("userId = " + userId);
        System.out.println("statusId = " + statusId);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", userId);
        User user = new User();
        if (statusId.equals("1")==true){
            user.setStatus("DISABLE");
        }else {
            user.setStatus("ENABLE");
        }
        int i = userAdminService.updateUser(user, wrapper);
        ResponseDTO<UserAdmin> responseDTO = new ResponseDTO<>();
        if (i==1){
            responseDTO.setState(200);
            responseDTO.setMessage("停用启用成功");
        }else {
            responseDTO.setState(500);
            responseDTO.setMessage("停用启用失败");
        }
        return responseDTO;
    }

    /**
     * 停用启用账号
     * @param userId
     * @param isDel
     * @return
     */
    @GetMapping("IsDelChanged/{userId}/{isDel}")
    public ResponseDTO<UserAdmin> IsDelChanged(@PathVariable("userId")Integer userId,
                                               @PathVariable("isDel")String isDel){
        System.out.println("userId = " + userId);
        System.out.println("isDel = " + isDel);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", userId);
        User user = new User();
        if (isDel.equals("1")){
            user.setIsDel(1);
        }else {
            user.setIsDel(0);
        }
        int i = userAdminService.updateUser(user, wrapper);
        ResponseDTO<UserAdmin> responseDTO = new ResponseDTO<>();
        if (i==1){
            responseDTO.setState(200);
            responseDTO.setMessage("停用启用成功");
        }else {
            responseDTO.setState(500);
            responseDTO.setMessage("停用启用失败");
        }
        return responseDTO;
    }

    /**
     * 校验旧密码输入是否正确
     * @param id
     * @param password
     * @return
     */
    @GetMapping("getAdminUserPassword/{id}")
    public ResponseDTO<String> getAdminUserPassword(@PathVariable("id")Integer id,
                                                    @RequestParam("password")String password)throws Exception{
        ResponseDTO<String> responseDTO = new ResponseDTO<>();
        UserAdmin userAdmin = userAdminService.selectById(id);
        String salt = userAdmin.getSalt();
        String pwd = salt + password;
        String md5 = MD5Util.md5Encode(password);
        System.out.println("md5 = " + md5);
        if (userAdmin.getPassword().equals(md5)==true){
            responseDTO.setState(200);
        }else {
            responseDTO.setState(500);
        }
        return responseDTO;
    }

    /**
     * 修改账户密码
     * @param id
     * @param password
     * @return
     */
    @GetMapping("updateAdminUserPassword/{id}")
    public ResponseDTO<String> updateAdminUserPassword(@PathVariable("id")Integer id,
                                                       @RequestParam("password")String password)throws Exception{
        ResponseDTO<String> responseDTO = new ResponseDTO<>();
        UserAdmin userAdmin = userAdminService.selectById(id);
        String salt = userAdmin.getSalt();
        String pwd = salt + password;
        String md5 = MD5Util.md5Encode(password);
        QueryWrapper<UserAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        UserAdmin userAdmin1 = new UserAdmin();
        userAdmin1.setPassword(md5);
        int update = userAdminService.update(userAdmin1, wrapper);
responseDTO.setState(200);
responseDTO.setMessage("更新密码成功");
        return responseDTO;
    }

    /**
     * 修改账号详情
     * @param id
     * @param name
     * @param phone
     * @param portrait
     * @return
     */
    @GetMapping("updateUserAll")
    public ResponseDTO<User> updateUserAll(@RequestParam("id")String id,
                                           @RequestParam("name")String name,
                                           @RequestParam("phone")String phone,
                                           @RequestParam("portrait")String portrait){
        ResponseDTO<User> responseDTO = new ResponseDTO<>();
        System.out.println("id = " + id);
        User user = userService.selectByPhone(phone);
        User user1 = userService.selectByName(name);
        System.out.println("user1 = " + user1);
        if (ValidateUtils.isMobile(phone) != true) {
            //手机号格式不对
            responseDTO.setState(500);
            responseDTO.setMessage("手机号格式不对!");
        }else {
        if (user != null && user.getId()!=Integer.parseInt(id)) {
            responseDTO.setState(500);
            responseDTO.setMessage("手机号已存在");
        } else if (user1 != null && user1.getId()!=Integer.parseInt(id)) {
            responseDTO.setState(500);
            responseDTO.setMessage("用户名已存在");
        }else {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id);
            User u = new User();
            u.setName(name);
            u.setPhone(phone);
            u.setPortrait(portrait);
            int i = userAdminService.updateUser(u, wrapper);
            if (i==1){
                responseDTO.setState(200);
            }else {
                responseDTO.setState(500);
                responseDTO.setMessage("修改用户失败");
            }
        }
        }
        return responseDTO;
    }

    /**
     * 添加账户
     * @param name
     * @param phone
     * @param password
     * @param portrait
     * @return
     * @throws Exception
     */
    @GetMapping("addUserAll")
    public ResponseDTO<User> addUserAll(@RequestParam("name")String name,
                                        @RequestParam("phone")String phone,
                                        @RequestParam("password")String password,
                                        @RequestParam("portrait")String portrait)throws Exception {
        ResponseDTO<User> responseDTO = new ResponseDTO<>();
        User user = userService.selectByPhone(phone);
        User user1 = userService.selectByName(name);
        if (ValidateUtils.isMobile(phone) != true) {
            //手机号格式不对
            responseDTO.setState(500);
            responseDTO.setMessage("手机号格式不对!");
            return responseDTO;
        }else {
            if (user != null) {
                responseDTO.setState(500);
                responseDTO.setMessage("手机号已存在");
            } else if (user1 != null) {
                responseDTO.setState(500);
                responseDTO.setMessage("用户名已存在");
            } else {
                User u = new User();
                u.setName(name);
                u.setPortrait(portrait);
                u.setPhone(phone);
                u.setStatus("ENABLE");
                u.setIsDel(0);
                u.setWeixin(0);
                Date date = new Date();
                System.out.println(date);
                //Date类型转String  //可指定任意的返回格式  yyyy
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateString = sdf.format(date);
                u.setCreateTime(dateString);
                u.setUpdateTime(dateString);
                // 获取用户密码
// 获取盐值
                String salt = RandomCharecters.getRandomString(4);
// 盐值加上密码
                String pwd = salt + password;
// 对加上盐值的密码进行加密
                String md5 = MD5Util.md5Encode(pwd);
// 把加密后的密码存到user对象中
                u.setPassword(md5);
// 把盐值存入user对象中
                u.setSalt(salt);
                int i = userService.insertUser(u);
                if (i == 1) {
                    responseDTO.setState(200);
                } else {
                    responseDTO.setState(500);
                    responseDTO.setMessage("新增用户失败");
                }
            }
        }
        return responseDTO;
    }

    /**
     * 过期、取消过期
     * @param id
     * @param timeId
     * @return
     */
    @GetMapping("updateTImeUser/{id}/{timeId}")
    public ResponseDTO<User> updateTImeUser(@PathVariable("id")Integer id,
                                            @PathVariable("timeId")Integer timeId){
        ResponseDTO<User> responseDTO = new ResponseDTO<>();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        User user = new User();
        user.setCredentialsNonExpired(timeId);
        int i = userAdminService.updateUser(user, wrapper);
        if (i==1){
            responseDTO.setState(200);
        }else {
            responseDTO.setState(500);
        }
        return responseDTO;
    }

    @GetMapping("getUsersComment")
    public ResponseDTO<List<User>> getUsers(){
        ResponseDTO<List<User>> responseDTO = new ResponseDTO<>();
        responseDTO.setContent(userService.getUserList(null,0,0));
        return responseDTO;
    }

}